package com.kcht.itsed.mws.subscribescheduler.comm;

import com.kcht.itsed.mws.subscribescheduler.biz.IConcreteReportSender;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 本地文件发送器
 * URL格式为:file://路径，注意，不支持Windows格式的磁盘盘符。只支持Linux的文件结构
 * 
 * @author zhangwenshuo
 *
 */
@Slf4j
public class LocalFileReportSender implements IConcreteReportSender{

	protected URI url;
	
	protected String path;
			
	private Map<String,String> queryMap;

	private boolean gziped = false;	//是否GZIP压缩了
	
	private AtomicLong al = new AtomicLong();
	
	public LocalFileReportSender(URI url) {
		this.url = url;
		path = url.getPath() + File.separator;
	}

	public LocalFileReportSender(URI url,Map<String,String> queryMap) {
		this(url);
		this.queryMap = queryMap;
		if(queryMap.containsKey("compress") && queryMap.get("compress").equals("gzip"))gziped = true;
	}

	@Override
	public void send(InputStream reportIS) throws ReportSendFailException {
		String fileName = path + "ALEREPORT_"+System.currentTimeMillis()+"_"+al.incrementAndGet()+ ".xml";
		if(gziped)fileName = fileName+".gz";
		try(FileOutputStream fos = new FileOutputStream(fileName)) {
			byte[] bytes = new byte[1024];
			int byteCount = 0;
			
			while((byteCount = reportIS.read(bytes,0,1000))!=-1) {
				fos.write(bytes, 0, byteCount);
				fos.flush();
			}
        } catch (FileNotFoundException e) {
			log.error("",e);
		} catch (IOException e) {
			log.error("",e);
        }finally {
        	try {
				reportIS.close();
			} catch (IOException e) {
				log.error("",e);
			}
        }
	}

	@Override
	public ReportSendingState getSendingState() {
		return ReportSendingState.SENDING;
	}
	
	
	
	
}
